package com.eyas.im.gui.swing.login;

import com.eyas.im.common.datasource.DataSourceUtils;
import com.eyas.im.gui.swing.common.CommonUtils;
import com.eyas.im.gui.swing.index.FriendListFrame;
import com.eyas.im.gui.swing.login.dao.IMUserInfo;
import com.eyas.im.gui.swing.login.exception.LoginInvalidException;
import com.eyas.im.gui.swing.register.RegisterFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import static java.awt.GridBagConstraints.*;

public class LoginFrame extends JFrame implements ActionListener, WindowListener {
    private final static Logger logger = LoggerFactory.getLogger(LoginFrame.class);
    private JTextField username_val;
    private JPasswordField password_val;

    public LoginFrame() {
        super("Eyas即时通讯系统");
        this.initialFrame();
    }

    private void initialFrame() {
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.setResizable(false);
        this.addWindowListener(this);
        Dimension screenSzie = Toolkit.getDefaultToolkit().getScreenSize();
        double x = screenSzie.getWidth();
        double y = screenSzie.getHeight();

        this.initailLoginFrame();
        this.pack();
        Dimension frameSize = this.getSize();
        double fx = frameSize.getWidth();
        double fy = frameSize.getHeight();
        this.setLocation((int) (x / 2 - fx / 2), (int) (y / 2 - fy / 2));
        this.setVisible(true);
    }

    private void initailLoginFrame() {
        JPanel jPanel = new JPanel();
        GridBagLayout gridBagLayout = new GridBagLayout();
        jPanel.setLayout(gridBagLayout);
        JLabel username = new JLabel("账号:");
        username.setFont(new Font("", Font.BOLD, 20));
        username_val = new JTextField(20);
        username_val.setFont(new Font("", Font.BOLD, 20));
        JLabel password = new JLabel("密码:");
        password.setFont(new Font("", Font.BOLD, 20));
        password_val = new JPasswordField(20);
        password_val.setFont(new Font("", Font.BOLD, 20));
        JButton jButton = new JButton("登录");
        jButton.setActionCommand("login");
        jButton.setFont(new Font("", Font.BOLD, 20));
        jButton.addActionListener(this);
        JButton registerButton = new JButton("注册");
        registerButton.setActionCommand("register");
        registerButton.setFont(new Font("", Font.BOLD, 20));
        registerButton.addActionListener(this);
        JButton initialDatabaseButton = new JButton("初始化数据库");
        initialDatabaseButton.setActionCommand("initialDB");
        initialDatabaseButton.setToolTipText("注意：如果数据库已经创建，再次执行可能回导致程序中断，也可能只发送warn日志，具体要根据appConfig.properties配置来判断");
        initialDatabaseButton.setFont(new Font("", Font.BOLD, 20));
        initialDatabaseButton.addActionListener(this);

        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new Insets(10, 5, 5, 10);
        jPanel.add(username, gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new Insets(10, 5, 5, 10);
        gridBagConstraints.fill = BOTH;
        jPanel.add(username_val, gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new Insets(10, 5, 5, 10);
        jPanel.add(password, gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new Insets(10, 5, 5, 10);
        gridBagConstraints.fill = BOTH;
        jPanel.add(password_val, gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new Insets(10, 10, 5, 10);
        gridBagConstraints.fill = BOTH;
        JPanel jButtonPanel = new JPanel();
        jButtonPanel.add(jButton);
        jButtonPanel.add(registerButton);
        jButtonPanel.add(initialDatabaseButton);
        jPanel.add(jButtonPanel, gridBagConstraints);

        this.add(jPanel);
    }

    /**
     * 登录验证
     *
     * @return 返回登录账号信息
     * @throws {@link LoginInvalidException}
     */
    private IMUserInfo checkDatabase(String userAccount, String password) throws Exception {
        try {
            java.util.List<IMUserInfo> userinfos = DataSourceUtils.INSTANCE.query("select * from im_user_info where useraccount=? and validflag='1'",
                    IMUserInfo.class, userAccount);
            if(userinfos==null) {
                throw new LoginInvalidException(LoginInvalidException.USERACCOUNT_NOT_EXISTS);
            }else {
                if(!userinfos.get(0).getUserPassword().equals(password)) {
                    throw new LoginInvalidException(LoginInvalidException.PASSWORD_NOT_CURRECT);
                }
            }

            return userinfos.get(0);
        } catch (LoginInvalidException e){
            throw e;
        }catch (Exception e) {
            logger.error("登录阶段，查询数据库出错", e);
            throw e;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("register")) {
            //弹出注册窗口
            new RegisterFrame();
        }else if(e.getActionCommand().equals("login")) {
            String usernameVal = username_val.getText();
            String passwordVal = String.valueOf(password_val.getPassword());
            if (usernameVal == null || usernameVal.equals("")) {
                JOptionPane.showMessageDialog(LoginFrame.this, "请输入用户名");
            } else if (passwordVal.equals("")) {
                JOptionPane.showMessageDialog(LoginFrame.this, "请输入密码");
            } else {
                //检查登录账号密码是否正确
                //正确的话，隐藏登录
                try {
                    IMUserInfo imUserInfo = LoginFrame.this.checkDatabase(usernameVal,passwordVal);
                    logger.debug("登录成功...");
                    Session.CURRENT_USER_INFO = imUserInfo;
                    //关闭登录窗口，打开FriendListFrame
                    this.dispose();
                    FriendListFrame.getInstance();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(LoginFrame.this,ex.getLocalizedMessage());
                }
            }
        }else if(e.getActionCommand().equals("initialDB")) {
            try {
                DataSourceUtils.INSTANCE.executeInitalSql();
            } catch (Exception ex) {
                logger.warn("初始化数据库过程中出现问题",ex);
                JOptionPane.showMessageDialog(LoginFrame.this,"初始化数据库过程中出现问题");
            }
        }
    }

    @Override
    public void windowOpened(WindowEvent e) {

    }

    @Override
    public void windowClosing(WindowEvent e) {
        this.dispose();
        CommonUtils.destoryApp();
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }
}
